package cn.hongxin.sap.conn.service.impl;

import cn.getech.poros.framework.common.api.RestResponse;
import cn.getech.poros.framework.common.api.ResultCode;
import cn.getech.poros.framework.common.exception.ServiceException;
import cn.hongxin.basic.business.client.BasicSystemDictClient;
import cn.hongxin.basic.business.response.DictItemResp;
import cn.hongxin.busi.common.constant.CacheConstant;
import cn.hongxin.busi.common.constant.CommonConstant;
import cn.hongxin.busi.common.constant.DataBaseConstant;
import cn.hongxin.busi.common.system.api.ISysBaseAPI;
import cn.hongxin.busi.common.system.vo.*;
import cn.hongxin.busi.common.util.SpringContextUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Description: 底层共通业务API，提供其他独立模块调用
 * @Author: scott
 * @Date:2019-4-20
 * @Version:V1.0
 */
@Slf4j
@Service
public class SysBaseApiImpl implements ISysBaseAPI {
    /**
     * 当前系统数据库类型
     */
    public static String DB_TYPE = "";

    @Autowired
    public BasicSystemDictClient basicSystemDictClient;


    @Override
    public void addLog(String LogContent, Integer logType, Integer operatetype) {

    }

    @Override
    @Cacheable(cacheNames = CacheConstant.SYS_USERS_CACHE, key = "#username")
    public LoginUser getUserByName(String username) {
        return null;
    }

    @Override
    public LoginUser getUserById(String id) {
        return null;
    }

    @Override
    public List<String> getRolesByUsername(String username) {
        return null;
    }

    @Override
    public List<String> getDepartIdsByUsername(String username) {
        return null;
    }

    @Override
    public List<String> getDepartNamesByUsername(String username) {
        return null;
    }

    @Override
    public String getDatabaseType() throws SQLException {
        DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
        return getDatabaseTypeByDataSource(dataSource);
    }

    @Override
    public List<DictModel> queryDictItemsByCode(String code) {

        List<DictModel> list = new ArrayList<>();
        try {
            RestResponse<List<DictItemResp>> restResponse = basicSystemDictClient.queryDictItemByCodeAndValue(code, null);
            if (restResponse.isSuccess()) {
                List<DictItemResp> dictItemResps = restResponse.getData();
                for (DictItemResp dictItemResp : dictItemResps) {
                    DictModel dictModel = new DictModel();

                    dictModel.setValue(dictItemResp.getItemValue());
                    dictModel.setText(dictItemResp.getItemText());
                    list.add(dictModel);
                }
                return list;
            }
        } catch (Exception e) {
            //log.error("[调用basicSystemDictClient失败-queryDictItemByCodeAndValue]", e);
        }
        return null;
    }

    @Override
    public List<DictModel> queryTableDictItemsByCode(String table, String text, String code) {

//        try {
//            RestResponse restResponse = busiSystemServiceClient.queryTableDictItemsByCode(table, text, code);
//            if (restResponse.isSuccess()) {
//                return (List<DictModel>) restResponse.getData();
//            }
//        } catch (Exception e) {
//            log.error("[调用系统服务失败-queryTableDictItemsByCode]", e);
//        }
        return null;

    }

    @Override
    public List<DictModel> queryAllDepartBackDictModel() {
//        return sysDictService.queryAllDepartBackDictModel();
        return null;
    }

    @Override
    public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent) {
        this.sendSysAnnouncement(fromUser, toUser, title, msgContent, CommonConstant.MSG_CATEGORY_2);
    }

    @Override
    public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory) {
    }

    @Override
    public void sendSysAnnouncement(String fromUser, String toUser, String title, String msgContent, String setMsgCategory, String busType, String busId) {

    }

    @Override
    public void updateSysAnnounReadFlag(String busType, String busId) {

    }

    @Override
    public String parseTemplateByCode(String templateCode, Map<String, String> map) {
        return null;
    }

    @Override
    public void sendSysAnnouncement(String fromUser, String toUser, String title, Map<String, String> map, String templateCode) {

    }

    @Override
    public void sendSysAnnouncement(String fromUser, String toUser, String title, Map<String, String> map, String templateCode, String busType, String busId) {

    }

    /**
     * 获取数据库类型
     *
     * @param dataSource
     * @return
     * @throws SQLException
     */
    private String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException {
        if ("".equals(DB_TYPE)) {
            Connection connection = dataSource.getConnection();
            try {
                DatabaseMetaData md = connection.getMetaData();
                String dbType = md.getDatabaseProductName().toLowerCase();
                if (dbType.indexOf("mysql") >= 0) {
                    DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
                } else if (dbType.indexOf("oracle") >= 0) {
                    DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
                } else if (dbType.indexOf("sqlserver") >= 0 || dbType.indexOf("sql server") >= 0) {
                    DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
                } else if (dbType.indexOf("postgresql") >= 0) {
                    DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
                } else {
                    throw new ServiceException(ResultCode.PARAM_VALID_ERROR);
                }
            } catch (Exception e) {
                //log.error(e.getMessage(), e);
            } finally {
                connection.close();
            }
        }
        return DB_TYPE;

    }

    @Override
    public List<DictModel> queryAllDict() {
        // 查询并排序
//        QueryWrapper<SysDict> queryWrapper = new QueryWrapper<SysDict>();
//        queryWrapper.orderByAsc("create_time");
//        List<SysDict> dicts = sysDictService.list(queryWrapper);
//        // 封装成 model
//        List<DictModel> list = new ArrayList<DictModel>();
//        for (SysDict dict : dicts) {
//            list.add(new DictModel(dict.getDictCode(), dict.getDictName()));
//        }
//
//        return list;
        return null;
    }

    @Override
    public List<SysCategoryModel> queryAllDSysCategory() {
//        List<SysCategory> ls = categoryMapper.selectList(null);
//        List<SysCategoryModel> res = oConvertUtils.entityListToModelList(ls, SysCategoryModel.class);
//        return res;
        return null;
    }

    @Override
    public List<DictModel> queryFilterTableDictInfo(String table, String text, String code, String filterSql) {
//        return sysDictService.queryTableDictItemsByCodeAndFilter(table, text, code, filterSql);
        return null;
    }

    @Override
    public List<String> queryTableDictByKeys(String table, String text, String code, String[] keyArray) {
//        return sysDictService.queryTableDictByKeys(table, text, code, keyArray);
        return null;
    }

    @Override
    public List<ComboModel> queryAllUser() {
        return null;
    }

    @Override
    public JSONObject queryAllUser(String[] userIds, int pageNo, int pageSize) {
        return null;
    }

    @Override
    public List<ComboModel> queryAllRole() {

        return null;
    }

    @Override
    public List<ComboModel> queryAllRole(String[] roleIds) {
        return null;
    }

    @Override
    public List<String> getRoleIdsByUsername(String username) {
        return null;
    }

    @Override
    public String getDepartIdsByOrgCode(String orgCode) {
//        return departMapper.queryDepartIdByOrgCode(orgCode);
        return null;
    }

    @Override
    public DictModel getParentDepartId(String departId) {
//        SysDepart depart = departMapper.getParentDepartId(departId);
//        DictModel model = new DictModel(depart.getId(), depart.getParentId());
//        return model;
        return null;
    }

    @Override
    public List<SysDepartModel> getAllSysDepart() {
        return null;
    }

    @Override
    public DynamicDataSourceModel getDynamicDbSourceById(String dbSourceId) {
        return null;
    }

    @Override
    public DynamicDataSourceModel getDynamicDbSourceByCode(String dbSourceCode) {
        return null;
    }

    @Override
    public List<String> getDeptHeadByDepId(String deptId) {
        return null;
    }

    @Override
    public String upload(MultipartFile file, String bizPath, String uploadType) {
        return null;
    }

}